<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <title>浏览器精确定位</title>
  <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
  <style>
    html,
    body,
    #container {
      height: 100%;
    }

    .info {
      width: 26rem;
    }
  </style>

<body>
  <div id='container'></div>
  <div class="info">
    <h4 id='status'></h4>
    <hr>
    <p id='result'></p>
  </div>
  <div class="input-card" style='width:28rem;'>
    <label style='color:grey'>逆地理编码，根据经纬度获取地址信息</label>
    <div class="input-item">
      <div class="input-item-prepend"><span class="input-item-text">经纬度</span></div>
      <input id='lnglat' type="text" value='116.39,39.9'>
    </div>
    <div class="input-item">
      <div class="input-item-prepend"><span class="input-item-text">地址</span></div>
      <input id='address' type="text" disabled>
    </div>
    <input id="regeo" type="button" class="btn" value="确认">
  </div>
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: "6659216496003bacfb3669434177369e",
    };
  </script>
  <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
  <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=8abe9d1ae5c264f4c316e5f87cf8095f"></script>
  <script type="text/javascript">
    var map = new AMap.Map('container', {
      resizeEnable: true
    });
    AMap.plugin('AMap.Geolocation', function () {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 25000,          //超过10秒后停止定位，默认：5s
        buttonPosition: 'RB',    //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition(function (status, result) {
        if (status == 'complete') {
          onComplete(result)
          regeoCode()
        } else {
          onError(result)
        }
      });
    });
    //解析定位结果
    function onComplete(data) {
      document.getElementById('status').innerHTML = '定位成功'
      var str = [];
      str.push('定位结果：' + data.position);
      str.push('定位类别：' + data.location_type);
      if (data.accuracy) {
        str.push('精度：' + data.accuracy + ' 米');
      }//如为IP精确定位结果则没有精度信息
      str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
      document.getElementById('result').innerHTML = str.join('<br>');
      document.getElementById('lnglat').value = data.position.lng + ',' + data.position.lat;
    }
    //解析定位错误信息
    function onError(data) {
      document.getElementById('status').innerHTML = '定位失败'
      document.getElementById('result').innerHTML = '失败原因排查信息:' + data.message;
    }
    var marker = new AMap.Marker();;
    // 逆地理编码函数
    function regeoCode() {
      var lnglatStr = document.getElementById('lnglat').value.split(',');
      var lnglat = [parseFloat(lnglatStr[0]), parseFloat(lnglatStr[1])];

      AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder({ city: null }); // 取消城市限制
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            document.getElementById('address').value = result.regeocode.formattedAddress;
            log.success('查询成功');
          } else {
            document.getElementById('address').value = "失败：" + (result.info || "请检查坐标格式");
            log.error(result.info);
          }
        });
      });

      // 更新地图标记
      marker.setPosition(lnglat);
      map.add(marker);
      map.setCenter(lnglat); // 居中显示
    }

    // 绑定按钮和回车事件
    document.getElementById("regeo").onclick = regeoCode;
    document.getElementById('lnglat').onkeydown = function (e) {
      if (e.keyCode === 13) regeoCode();
    };

    // 地图点击事件
    map.on('click', function (e) {
      document.getElementById('lnglat').value = e.lnglat.getLng() + ',' + e.lnglat.getLat();
      regeoCode();
    });

    var regeoBtn = document.getElementById('regeo');
    var dizhi=localStorage.getItem("dizhi")
    if (regeoBtn) {
      regeoBtn.addEventListener('click', function () {
        self.location.href = (`http://localhost:5173${dizhi}`);
        // 更改表单中的地址信息，其余信息不变
        localStorage.setItem('AddressForm', JSON.stringify({ ...JSON.parse(localStorage.getItem('AddressForm')), address: document.getElementById('address').value }));
      });
    }

  </script>
</body>

</html>